<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<script type="text/javascript">
    require([ "dojo/_base/array", "dojo/_base/xhr", "dojo/request", "dojo/topic", "dojo/json" ], function(array, xhr,
            request, topic, JSON) {
        var resetForm = "sysmenu/insertOrUpdate";
        var refreshTree = "sysmenu/refreshZtree";
        var zTreeId = "menuTree";
        sysmenuRestForm = function(formId) {
            var form = dijit.byId(formId);
            var rawData = form.getValues();
            form.reset();
            if (formId.indexOf('UFD') != -1) {
                var zTree = jQuery.fn.zTree.getZTreeObj(zTreeId);
                var sysmenu = zTree.getSelectedNodes();
                form.setValues(sysmenu[0]);
            } else {
                form.setValues({
                    pid : rawData.pid
                });
            }
        };
        topic.subscribe(resetForm, sysmenuRestForm);
        var syncDB = function(url, jsonData) {
            request.post(url, {
                data : jsonData,
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(function(response) {
                var resp = JSON.parse(response);
                topic.publish("notifyMsgTopic", {
                    message : resp.msg || "操作成功!",
                    type : "message",
                    duration : 1000
                });
                topic.publish(refreshTree);
            }, function(error) {
                alert(error);
            });
        };
        sysmenuSubmitForm = function(formId, type) {
            var url = "sysmenu/insert";
            if (type == 'u') {
                url = "sysmenu/update";
            }
            var form = dijit.byId(formId);
            if (form.isValid()) {
                var jsonData = form.getValues();
                if (type != 'u') {
                    syncDB(url, JSON.stringify(jsonData));
                    form.hide();
                } else {
                    var uList = [];
                    uList[0] = jsonData;
                    syncDB(url, JSON.stringify(uList));
                }
                topic.publish(resetForm, formId);
            } else {
                form.validate();
            }
        };
        sysmenuDelete = function() {
            var zTree = jQuery.fn.zTree.getZTreeObj(zTreeId);
            var nodes = zTree.getCheckedNodes(true);
            if (nodes.length > 0) {
                if (confirm('确认删除所选定的项？')) {
                    var sysmenu = {};
                    sysmenu.id = '';
                    array.forEach(nodes, function(entry, i) {
                        sysmenu.id += entry.menuid + ",";
                    });
                    syncDB("sysmenu/delete", JSON.stringify(sysmenu));
                    var handle = topic.subscribe(refreshTree, function() {
                        zTree.reAsyncChildNodes(null, "refresh");
                        handle.remove();
                    });
                }
            } else {
                alert('请选择至少一条数据!');
            }
        };
        // zTree 
        var addHoverDom = function(treeId, treeNode) {
            var sObj = jQuery("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || jQuery("#addBtn_" + treeNode.id).length > 0)
                return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.id
                    + "' title='新增节点' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = jQuery("#addBtn_" + treeNode.id);
            if (btn) {
                btn.bind("click", function() {
                    var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
                    if (!treeNode.open) {
                        zTree.expandNode(treeNode);
                    }
                    var sysmenuIFD = dijit.byId('sysmenuIFD');
                    sysmenuIFD.setValues({
                        pid : treeNode.menuid
                    });
                    sysmenuIFD.show();
                    var handle = topic.subscribe(refreshTree, function() {
                        if (treeNode.isParent) {
                            zTree.reAsyncChildNodes(treeNode, "refresh");
                        } else {
                            zTree.reAsyncChildNodes(treeNode.getParentNode(), "refresh");
                        }
                        handle.remove();
                    });
                    return false;
                });
            }
        };
        var removeHoverDom = function(treeId, treeNode) {
            jQuery("#addBtn_" + treeNode.id).unbind().remove();
        };
        var filter = function(treeId, parentNode, childNodes) {
            if (!childNodes)
                return null;
            for ( var i = 0, l = childNodes.length; i < l; i++) {
                childNodes[i].menuname = childNodes[i].menuname.replace(/\.n/g, '.');
            }
            return childNodes;
        };
        var onClick = function(event, treeId, treeNode, clickFlag) {
            var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
            var sysmenuIFD = dijit.byId('sysmenuUFD');
            var sysmenuUSB = dijit.byId('sysmenuUSB');
            var sysmenuURB = dijit.byId('sysmenuURB');
            sysmenuIFD.setValues(treeNode);
            sysmenuUSB.set('disabled', null);
            sysmenuURB.set('disabled', null);
            var handle = topic.subscribe(refreshTree, function() {
                sysmenuUSB.set('disabled', true);
                sysmenuURB.set('disabled', true);
                zTree.reAsyncChildNodes(treeNode.getParentNode() || treeNode, "refresh");
                handle.remove();
            });
        };
        var dropPrev = function(treeId, nodes, targetNode) {
            if (targetNode && targetNode.pid != null) {
                return true;
            }
            return false;
        };
        var dropInner = function(treeId, nodes, targetNode) {
            if (targetNode && targetNode.pid != null) {
                return true;
            }
            return false;
        };
        var dropNext = function(treeId, nodes, targetNode) {
            if (targetNode && targetNode.pid != null) {
                return true;
            }
            return false;
        };
        var onDrop = function(event, treeId, treeNodes, targetNode, moveType) {
            var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
            var treeNode = treeNodes[0];
            var pNode = treeNode.getParentNode();
            var nodes = zTree.getNodesByParam("pid", pNode.menuid, pNode);
            array.forEach(nodes, function(item, index) {
                item.displayorder = item.level + "" + zTree.getNodeIndex(item);
            });
            request.post("sysmenu/update", {
                data : JSON.stringify(nodes),
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(function(response) {
                var resp = JSON.parse(response);
                topic.publish("notifyMsgTopic", {
                    message : resp.msg || "操作成功!",
                    type : "message",
                    duration : 1000
                });
            }, function(error) {
                alert(error);
            });
        };
        var setting = {
            async : {
                enable : true,
                url : "sysmenu/zTree",
                autoParam : [ "menuid" ],
                dataFilter : filter
            },
            check : {
                enable : true,
                chkboxType : {
                    "Y" : "s",
                    "N" : "p"
                }
            },
            view : {
                addHoverDom : addHoverDom,
                removeHoverDom : removeHoverDom,
                selectedMulti : false
            },
            edit : {
                drag : {
                    autoExpandTrigger : true,
                    prev : dropPrev,
                    inner : dropInner,
                    next : dropNext
                },
                enable : true,
                editNameSelectAll : true,
                showRenameBtn : false,
                showRemoveBtn : false
            },
            data : {
                key : {
                    name : 'menuname',
                    url : 'menuurl'
                },
                simpleData : {
                    enable : true,
                    idKey : 'menuid',
                    pIdKey : 'pid'
                }
            },
            callback : {
                onClick : onClick,
                onDrop : onDrop
            }
        };
        jQuery.fn.zTree.init(jQuery("#menuTree"), setting);
    });
</script>
<div data-dojo-type="dijit/Dialog" id="sysmenuIFD" title="新增">
  <div class="dijitDialogPaneContentArea">
    <table>
      <tr>
        <td><label for="menuname">菜单名称: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true"
          type="text" name="menuname"></td>
      </tr>
      <tr>
        <td><label for="menuurl">菜单链接: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true"
          type="text" name="menuurl"></td>
      </tr>
      <tr style="display: none;">
        <td><label for="pid">父菜单: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true"
          type="text" name="pid"></td>
      </tr>
      <tr style="display: none;">
        <td><label for="displayorder">显示顺序: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true"
          type="text" name="displayorder" value="1"></td>
      </tr>
      <tr>
        <td><label for="description">描述: </label></td>
        <td><input data-dojo-type="dijit/form/Textarea" data-dojo-props="trim:true" type="textarea"
          name="description"></td>
      </tr>
    </table>
  </div>
  <div class="dijitDialogPaneActionBar">
    <button data-dojo-type="dijit/form/Button" type="button" onclick="sysmenuSubmitForm('sysmenuIFD','i')">保存</button>
    <button data-dojo-type="dijit/form/Button" type="button" onclick="sysmenuRestForm('sysmenuIFD');">重置</button>
  </div>
</div>
<fieldset>
  <legend>&nbsp;&nbsp;信息选项&nbsp;&nbsp;</legend>
  <form id="querySysMenuForm" data-dojo-type="dijit/form/Form" method="post">
    <div style="margin-left: 5px;">
      <table>
        <tr>
          <td><label for="menuname">菜单名称: </label></td>
          <td><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="menuname"></td>
        </tr>
      </table>
    </div>
  </form>
  <div style="padding: 5px;">
    <button id="sysmenuDeleteBtn" data-dojo-type="dijit/form/Button" type="button" label="删除" onclick="sysmenuDelete();"></button>
  </div>
</fieldset>
<div style="float: left; margin: 10px;">
  <fieldset style="width: 420px; height: 360px;">
    <legend>&nbsp;&nbsp;明细&nbsp;&nbsp;</legend>
    <form id="sysmenuUFD" data-dojo-type="dijit/form/Form" method="post">
      <div style="margin: 0 20px;">
        <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true"
          type="text" name="menuid" style="display: none;">
        <table style="width: 400px;" cellspacing="18px">
          <tr>
            <td><label for="menuname">菜单名称: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
              name="menuname" style="width: 250px;"></td>
          </tr>
          <tr>
            <td><label for="menuurl">菜单链接: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
              name="menuurl" style="width: 250px;"></td>
          </tr>
          <tr style="display: none;">
            <td><label for="pid">父菜单: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
              name="pid" style="width: 250px;"></td>
          </tr>
          <tr style="display: none;">
            <td><label for="displayorder">显示顺序: </label></td>
            <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
              name="displayorder" style="width: 250px;"></td>
          </tr>
          <tr>
            <td><label for="description">描述: </label></td>
            <td><textarea data-dojo-type="dijit/form/SimpleTextarea" data-dojo-props="trim:true" name="description"
                rows=3 cols=30></textarea></td>
          </tr>
        </table>
      </div>
      <div style="margin: 10px; float: right;">
        <button id="sysmenuUSB" data-dojo-type="dijit/form/Button" data-dojo-props="disabled:true" type="button"
          onclick="sysmenuSubmitForm('sysmenuUFD','u')">保存</button>
        <button id="sysmenuURB" data-dojo-type="dijit/form/Button" data-dojo-props="disabled:true" type="button"
          onclick="sysmenuRestForm('sysmenuUFD');">重置</button>
      </div>
    </form>
  </fieldset>
</div>
<div style="float: right;">
  <ul id="menuTree" class="ztree" style="margin-top: 10px; width: 358px; height: 350px; overflow-y: scroll;"></ul>
</div>
